<template>
  <el-dialog
    title="SQL编辑器"
    v-model="dialogVisible"
    width="90%"
    :close-on-click-modal="false"
    class="sql-editor-dialog"
  >
    <el-container class="editor-container">
      <!-- 左侧数据源和表结构 -->
      <el-aside width="250px" class="structure-panel">
        <el-form>
          <el-form-item label="数据源">
            <el-select
              v-model="selectedDataSource"
              placeholder="请选择数据源"
              :loading="loadingDataSources"
              @change="handleDataSourceChange"
            >
              <el-option
                v-for="source in dataSources"
                :key="source.id"
                :label="source.name"
                :value="source.id"
              />
            </el-select>

            <div
              v-if="dataSources.length === 0 && !loadingDataSources"
              class="empty-tip"
            >
              未找到可用的数据源，请先在
              <el-link type="primary" @click="goToDataSource"
                >数据源管理</el-link
              >
              中添加数据源
            </div>
          </el-form-item>
        </el-form>

        <div v-if="selectedDataSource" class="structure-panel-header">
          <span class="structure-title">数据库结构</span>
          <el-input
            v-model="structureFilter"
            placeholder="过滤表名"
            prefix-icon="Search"
            clearable
            size="small"
          />
        </div>

        <div class="structure-tree">
          <div v-if="loadingStructure" class="loading-structure">
            <el-skeleton :rows="5" animated />
          </div>
          <div v-else-if="structureError" class="structure-error">
            <el-alert
              title="加载结构失败"
              type="error"
              :closable="false"
              show-icon
            >
              <template #default>
                <p>{{ structureError }}</p>
                <el-button
                  type="primary"
                  size="small"
                  @click="loadDbStructure(selectedDataSource)"
                >
                  重试
                </el-button>
              </template>
            </el-alert>
          </div>
          <div v-else-if="dbStructure.length === 0" class="empty-structure">
            <el-empty description="未找到数据库结构" />
          </div>
          <el-tree
            v-else
            :data="filteredStructure"
            :props="treeProps"
            node-key="id"
            default-expand-all
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="tree-node">
                <el-icon>
                  <Folder v-if="data.type === 'folder'" />
                  <Document v-else-if="data.type === 'table'" />
                  <View v-else-if="data.type === 'view'" />
                </el-icon>
                <span>{{ node.label }}</span>
              </span>
            </template>
          </el-tree>
        </div>
      </el-aside>

      <!-- 右侧 SQL 编辑和结果展示 -->
      <el-container class="main-panel">
        <el-header height="40px" class="toolbar">
          <el-button-group>
            <el-button type="primary" @click="handleExecute">
              <el-icon><VideoPlay /></el-icon>执行
            </el-button>
            <el-button @click="handleFormat">
              <el-icon><Operation /></el-icon>格式化
            </el-button>
          </el-button-group>
        </el-header>

        <el-main class="editor-main">
          <el-container direction="vertical">
            <!-- SQL 编辑区域 -->
            <div class="sql-area">
              <el-input
                v-model="sql"
                type="textarea"
                :rows="8"
                placeholder="请输入SQL语句"
              />
            </div>

            <!-- 结果展示区域 -->
            <div class="result-area" v-loading="executing">
              <div v-if="previewData.length" class="result-header">
                <div>
                  <span class="result-title">查询结果</span>
                  <el-tag
                    v-if="lastQueryDataSourceType"
                    size="small"
                    class="datasource-type-tag"
                  >
                    {{ lastQueryDataSourceType }}
                  </el-tag>
                </div>
                <span class="result-count"
                  >共 {{ previewData.length }} 条记录</span
                >
              </div>

              <el-table
                v-if="previewData.length"
                :data="previewData"
                border
                style="width: 100%"
                height="250"
                :max-height="250"
              >
                <el-table-column
                  v-for="col in previewColumns"
                  :key="col"
                  :prop="col"
                  :label="col"
                  :min-width="120"
                  show-overflow-tooltip
                />
              </el-table>

              <div v-else class="no-data">
                <el-empty
                  :description="executing ? '正在执行...' : '暂无数据'"
                  :image-size="60"
                >
                  <template #description>
                    <p>
                      {{ executing ? "正在执行查询..." : "执行查询以查看结果" }}
                    </p>
                  </template>
                </el-empty>
              </div>
            </div>
          </el-container>
        </el-main>
      </el-container>
    </el-container>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import {
  Folder,
  Document,
  View,
  VideoPlay,
  Operation,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import {
  getDataSourceList,
  getDataSourceStructure,
  previewSql,
} from "@/api/dataSource";
import type {
  DataSource,
  DbStructure,
  SqlPreviewResult,
} from "@/types/dataSource";
import MonacoEditor from "@/components/MonacoEditor.vue";
import type { ApiConfig } from "@/types/api";
import { PropType } from "vue";
import { useRouter } from "vue-router";

interface TreeNode {
  id: string;
  label: string;
  type: "folder" | "table" | "view";
  children?: TreeNode[];
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  apiData: {
    type: Object as PropType<ApiConfig | null>,
    default: null,
  },
});

const emit = defineEmits<{
  "update:visible": [value: boolean];
  confirm: [sqlConfig: any];
}>();

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit("update:visible", value),
});

// 数据源相关
const dataSources = ref<DataSource[]>([]);
const selectedDataSource = ref<number>();

// 数据库结构相关
const dbStructure = ref<DbStructure[]>([]);
const treeProps = {
  label: "label",
  children: "children",
};

// SQL 编辑和执行相关
const sql = ref("");
const executing = ref(false);
const previewData = ref<any[]>([]);
const previewColumns = ref<string[]>([]);

// 添加数据源加载状态
const loadingDataSources = ref(false);

// 添加状态变量
const loadingStructure = ref(false);
const structureError = ref("");

// 添加数据源缓存机制
const dataSourceCache = ref(new Map());

// 添加结构过滤功能
const structureFilter = ref("");

// 添加上次查询的数据源类型
const lastQueryDataSourceType = ref("");

const router = useRouter();

// 当编辑数据变化时，填充SQL
watch(
  () => props.apiData,
  (newVal) => {
    console.log("SQL编辑器 - apiData 变化:", newVal);

    // 同步 SQL
    if (newVal?.config?.sql) {
      sql.value = newVal.config.sql;
    } else {
      sql.value = "SELECT * FROM table_name\nWHERE condition\nLIMIT 10";
    }

    // 同步数据源 ID
    if (newVal?.config?.dataSourceId) {
      selectedDataSource.value = newVal.config.dataSourceId;
      // 自动加载该数据源的结构
      loadDbStructure(selectedDataSource.value);
    }
  },
  { immediate: true }
);

// 改进数据源加载方法，添加缓存
const loadDataSources = async () => {
  loadingDataSources.value = true;
  console.log("SQL编辑器 - 开始加载数据源列表");

  try {
    const result = await getDataSourceList({ page: 1, pageSize: 100 });
    console.log("SQL编辑器 - 数据源API返回结果:", result);

    if (result?.data?.data?.list) {
      dataSources.value = result.data.data.list;
      console.log(
        "SQL编辑器 - 成功加载数据源，数量:",
        dataSources.value.length
      );

      // 将数据源信息保存到缓存中
      dataSources.value.forEach((ds) => {
        dataSourceCache.value.set(ds.id, ds);
      });

      // 如果当前编辑的 API 有数据源 ID，自动选择该数据源
      if (props.apiData?.config?.dataSourceId) {
        console.log(
          "SQL编辑器 - 自动选择数据源ID:",
          props.apiData.config.dataSourceId
        );
        selectedDataSource.value = props.apiData.config.dataSourceId;

        // 加载该数据源的结构
        await loadDbStructure(selectedDataSource.value);
      }
    } else {
      console.error("SQL编辑器 - API返回的数据结构不符合预期:", result);
      dataSources.value = [];
    }
  } catch (error) {
    console.error("SQL编辑器 - 加载数据源失败:", error);
    ElMessage.error("加载数据源列表失败");
    dataSources.value = [];
  } finally {
    loadingDataSources.value = false;
  }
};

// 修改 loadDbStructure 方法，增加加载状态和错误处理
const loadDbStructure = async (dataSourceId: number) => {
  if (!dataSourceId) {
    console.warn("SQL编辑器 - 未提供数据源ID，无法加载结构");
    return;
  }

  console.log("SQL编辑器 - 开始加载数据库结构, 数据源ID:", dataSourceId);
  loadingStructure.value = true;
  structureError.value = "";
  dbStructure.value = []; // 清空现有结构

  try {
    const result = await getDataSourceStructure(dataSourceId);
    console.log("SQL编辑器 - 数据库结构返回结果:", result);

    if (result?.data?.data) {
      dbStructure.value = result.data.data;
      console.log(
        "SQL编辑器 - 成功加载数据库结构，表数量:",
        dbStructure.value.length
      );
    } else {
      console.error("SQL编辑器 - API返回的数据库结构不符合预期:", result);
      structureError.value = "返回数据格式不正确";
    }
  } catch (error) {
    console.error("SQL编辑器 - 加载数据库结构失败:", error);
    structureError.value = error.message || "网络错误";
  } finally {
    loadingStructure.value = false;
  }
};

// 添加获取数据源类型的功能
const currentDataSource = computed(() => {
  if (!selectedDataSource.value || !dataSources.value) return null;
  return (
    dataSources.value.find((ds) => ds.id === selectedDataSource.value) || null
  );
});

// 添加数据源类型的计算属性
const currentDataSourceType = computed(() => {
  if (!currentDataSource.value) return "";
  return currentDataSource.value.type.toLowerCase();
});

// 修改 handleDataSourceChange 函数，记录数据源类型
const handleDataSourceChange = (dataSourceId: number) => {
  if (!dataSourceId) return;

  console.log("SQL编辑器 - 数据源变更为:", dataSourceId);
  const ds = dataSources.value.find((d) => d.id === dataSourceId);
  console.log("SQL编辑器 - 数据源类型:", ds?.type);

  // 清空之前的数据库结构和错误信息
  dbStructure.value = [];
  structureError.value = "";

  // 根据数据源类型设置默认SQL
  if (ds) {
    setDefaultSqlByDataSourceType(ds.type);
  }

  // 加载新数据源的结构
  loadDbStructure(dataSourceId);
};

// 设置基于数据源类型的默认SQL
const setDefaultSqlByDataSourceType = (dataSourceType: string) => {
  const type = dataSourceType.toLowerCase();

  if (
    sql.value &&
    sql.value !== "SELECT * FROM table_name\nWHERE condition\nLIMIT 10"
  ) {
    // 用户已修改过SQL，不自动改变
    return;
  }

  switch (type) {
    case "mysql":
      sql.value = "SELECT * FROM users LIMIT 10";
      break;
    case "postgresql":
      sql.value = "SELECT * FROM accounts LIMIT 10";
      break;
    case "sqlserver":
      sql.value = "SELECT * FROM Employees";
      break;
    case "oracle":
      sql.value = "SELECT * FROM EMPLOYEES WHERE ROWNUM <= 10";
      break;
    default:
      sql.value = "SELECT * FROM users LIMIT 10";
  }
};

// 处理树节点点击
const handleNodeClick = (data: TreeNode) => {
  if (data.type === "table" || data.type === "view") {
    sql.value += `\nSELECT * FROM ${data.label};`;
  }
};

// 修改 handleExecute 方法，记录数据源类型
const handleExecute = async () => {
  if (!selectedDataSource.value) {
    ElMessage.warning("请先选择数据源");
    return;
  }

  if (!sql.value.trim()) {
    ElMessage.warning("SQL 语句不能为空");
    return;
  }

  executing.value = true;

  try {
    const result = await previewSql(selectedDataSource.value, sql.value);
    console.log("SQL执行结果:", result);

    if (result.data && result.data.data) {
      // 更新结果数据
      previewData.value = result.data.data;
      previewColumns.value = result.data.columns;

      // 记录数据源类型
      if (result.data.dataSourceType) {
        lastQueryDataSourceType.value = result.data.dataSourceType;
        console.log(
          `在 ${result.data.dataSourceType} 数据库上执行查询，返回 ${previewData.value.length} 条记录`
        );
      }

      ElMessage.success(`执行成功，返回 ${previewData.value.length} 条记录`);
    } else {
      // 重置数据
      previewData.value = [];
      previewColumns.value = [];
      lastQueryDataSourceType.value = "";
      ElMessage.info("查询未返回数据");
    }
  } catch (error) {
    console.error("执行 SQL 失败:", error);
    ElMessage.error(`执行失败: ${error.message || "未知错误"}`);
    previewData.value = [];
    previewColumns.value = [];
  } finally {
    executing.value = false;
  }
};

// 格式化 SQL
const handleFormat = () => {
  // TODO: 实现 SQL 格式化
  ElMessage.success("格式化完成");
};

const handleCancel = () => {
  dialogVisible.value = false;
  sql.value = "";
  selectedDataSource.value = undefined;
  previewData.value = [];
  previewColumns.value = [];
};

const handleConfirm = () => {
  if (!selectedDataSource.value) {
    ElMessage.warning("请选择数据源");
    return;
  }

  if (!sql.value.trim()) {
    ElMessage.warning("SQL 语句不能为空");
    return;
  }

  // 构建完整的 SQL 配置
  const sqlConfig = {
    sql: sql.value,
    dataSourceId: selectedDataSource.value,
    params: [], // 可以从 SQL 中解析参数
  };

  console.log("SQL编辑器 - 确认 SQL 配置:", sqlConfig);
  emit("confirm", sqlConfig);
  dialogVisible.value = false;
};

// 添加导航到数据源管理页面的方法
const goToDataSource = () => {
  dialogVisible.value = false; // 关闭当前对话框
  router.push("/data-source");
};

// 添加一个计算属性，获取当前选中的数据源名称
const currentDataSourceName = computed(() => {
  if (!selectedDataSource.value) return "";

  const ds = dataSourceCache.value.get(selectedDataSource.value);
  return ds ? ds.name : "";
});

// 添加过滤后的结构计算属性
const filteredStructure = computed(() => {
  if (!dbStructure.value || dbStructure.value.length === 0) {
    return [];
  }

  if (!structureFilter.value) {
    return dbStructure.value;
  }

  const filter = structureFilter.value.toLowerCase();

  // 对树结构进行过滤，保留匹配的节点
  return dbStructure.value
    .map((category) => {
      // 深拷贝避免修改原数据
      const copiedCategory = JSON.parse(JSON.stringify(category));

      if (copiedCategory.children && copiedCategory.children.length) {
        copiedCategory.children = copiedCategory.children.filter((child) =>
          child.label.toLowerCase().includes(filter)
        );
      }

      // 只返回有匹配子节点的分类
      return copiedCategory.children && copiedCategory.children.length
        ? copiedCategory
        : null;
    })
    .filter(Boolean); // 过滤掉空值
});

// 修改加载逻辑，确保组件初始化时设置正确的数据源
onMounted(async () => {
  console.log("SQL编辑器 - 组件挂载");

  // 加载数据源列表
  await loadDataSources();

  // 如果有apiData且包含dataSourceId，则自动选择该数据源
  if (props.apiData?.config?.dataSourceId) {
    console.log(
      "SQL编辑器 - 从apiData中获取数据源ID:",
      props.apiData.config.dataSourceId
    );
    selectedDataSource.value = props.apiData.config.dataSourceId;

    // 自动加载数据库结构
    loadDbStructure(selectedDataSource.value);

    // 自动执行一次SQL，获取预览数据
    if (sql.value) {
      handleExecute();
    }
  } else if (dataSources.value && dataSources.value.length > 0) {
    // 如果没有指定数据源但有可用数据源，选择第一个
    console.log("SQL编辑器 - 自动选择第一个数据源:", dataSources.value[0].id);
    selectedDataSource.value = dataSources.value[0].id;

    // 设置默认SQL
    setDefaultSqlByDataSourceType(dataSources.value[0].type);

    // 加载数据库结构
    loadDbStructure(selectedDataSource.value);
  }
});
</script>

<style scoped>
.sql-editor-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.editor-container {
  height: 70vh;
}

.structure-panel {
  padding: 20px;
  border-right: 1px solid var(--el-border-color-light);
}

.structure-tree {
  margin-top: 20px;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
}

.main-panel {
  background-color: var(--el-bg-color);
}

.toolbar {
  display: flex;
  align-items: center;
  padding: 0 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.editor-main {
  padding: 20px;
}

.sql-area {
  margin-bottom: 20px;
}

.result-area {
  flex: 1;
  min-height: 250px;
  border: 1px solid var(--el-border-color-light);
  border-radius: 4px;
}

.no-data {
  height: 250px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--el-text-color-secondary);
}

.dialog-footer {
  padding: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  border-top: 1px solid var(--el-border-color-light);
}

/* 添加空数据源提示样式 */
.empty-tip {
  margin-top: 8px;
  font-size: 13px;
  color: var(--el-text-color-secondary);
}

/* 新增加载状态和错误提示的样式 */
.loading-structure,
.structure-error,
.empty-structure {
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
}

.structure-error {
  padding: 0 10px;
}

/* 添加表格标题相关样式 */
.result-header {
  padding: 10px;
  display: flex;
  justify-content: space-between;
  background-color: var(--el-fill-color-light);
  border-bottom: 1px solid var(--el-border-color-light);
}

.result-title {
  font-weight: bold;
}

.result-count {
  color: var(--el-text-color-secondary);
  font-size: 0.9em;
}

.structure-panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.structure-title {
  font-weight: bold;
}

/* 添加数据源类型标签样式 */
.datasource-type-tag {
  margin-left: 8px;
  text-transform: uppercase;
}
</style> 